package com.fintech.pangu.actuate.metrics.aop;

import com.fintech.pangu.actuate.metrics.annotation.Gauged;
import com.fintech.pangu.actuate.metrics.util.MetricsUtil;
import io.micrometer.core.annotation.Incubating;
import io.micrometer.core.lang.NonNullApi;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;
import java.util.concurrent.atomic.AtomicInteger;

@Aspect
@NonNullApi
@Incubating(since = "1.0.0")
public class GaugeAspect {

    private static final String DEFAULT_METRIC_NAME = "gauged";

    @Around("@annotation(gauge)")
    public Object gaugeMethod(ProceedingJoinPoint pjp, Gauged gauge) throws Throwable {

        Method method = ((MethodSignature) pjp.getSignature()).getMethod();
        String methodName = method.getName();
        String name = method.toGenericString();
        String value = gauge.value().trim().isEmpty() ? methodName + "_" + DEFAULT_METRIC_NAME : gauge.value();
        String description = gauge.description();
        String[] extraTags = gauge.extraTags();
        AtomicInteger atomicInteger = MetricsUtil.recordGauge(value, description,extraTags);
        try {
            Object proceed = pjp.proceed();
            atomicInteger.incrementAndGet();
            return proceed;
        } catch (Throwable throwable) {
            atomicInteger.decrementAndGet();
            throw throwable;
        }

    }

}
